﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.PrizeService;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace SalaryChannel
{
    public partial class PrizeControl : UserControl
    {
        private PrizeServiceClient _pssService = null;
        private static OperationContext _pssPC = null;
        public PrizeServiceClient PrzService
        {
            get
            {
                if (_pssService == null)
                {
                    _pssService = new PrizeServiceClient();

                    OperationContext.Current = new OperationContext((IContextChannel)_pssService.InnerChannel);
                    MessageHeader header = MessageHeader.CreateHeader("uafcztga", "", ServiceInstance.UserName);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    header = MessageHeader.CreateHeader("xufasft", "", ServiceInstance.Password);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    _pssPC = OperationContext.Current;
                }
                else
                {
                    OperationContext.Current = _pssPC;
                }
                return _pssService;
            }
            set { _pssService = value; }
        }

        public PrizeControl()
        {
            InitializeComponent();
            PrzService.GetPrizeCompleted += new EventHandler<GetPrizeCompletedEventArgs>(PrzService_GetPrizeCompleted);
            PrzService.GetPrizeItemsByIDCompleted += new EventHandler<GetPrizeItemsByIDCompletedEventArgs>(PrzService_GetPrizeItemsByIDCompleted);
            PrzService.UploadPrizeResultCompleted += new EventHandler<UploadPrizeResultCompletedEventArgs>(PrzService_UploadPrizeResultCompleted);
            PrzService.IsUserPrizeDoneCompleted += new EventHandler<IsUserPrizeDoneCompletedEventArgs>(PrzService_IsUserPrizeDoneCompleted);
        }

        void PrzService_GetPrizeCompleted(object sender, GetPrizeCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询奖项类别失败");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有可用的奖项类别");
                }
                else
                {
                    PrizeCM.Items.Clear();
                    foreach (var a in e.Result)
                    {
                        PrizeCM.Items.Add(a);
                    }

                }
            }
            finally
            {
                App.IsRunning = false;
            }
        }
        public void Initiallize()
        {
            this.PrizeMngPage.Visibility = App.IsAuth(23)?System.Windows.Visibility.Visible: System.Windows.Visibility.Collapsed;
            this.RunLoading.Visibility = System.Windows.Visibility.Collapsed;
            this.PrizeResultTB.Visibility = System.Windows.Visibility.Visible;
            this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";
            this.RunBtn.Content = "开始";

            try
            {
                PrzService.GetPrizeAsync(false,App.CurrentUser.CountyCode);

                App.IsRunning = true;
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        private void PrizeCM_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PrizeCM.SelectedItem == null)
            {
                return;
            }
            short id = (short)App.GetID(PrizeCM.SelectedItem.ToString());

            try
            {
                PrzService.GetPrizeItemsByIDAsync(id);
                PrizeItemList.ItemsSource = null;
                App.IsRunning = true;
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }
      
        void PrzService_GetPrizeItemsByIDCompleted(object sender, GetPrizeItemsByIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询奖项设置失败,服务器异常");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有可用的奖项设置");
                }
                else
                {
                    PrizeItemList.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("查询奖项设置失败");

            }
            finally
            {
                App.IsRunning = false;
            }

        }
        private void RunBtn_Click(object sender, RoutedEventArgs e)
        {

            if (RunBtn.Content.ToString() == "开始")
            {
                if (!App.PhoneRegex.IsMatch(PhoneTB.Text))
                {
                    App.MessageBox.ShowDialog("用户号码不合法");
                    return;
                }
                PrizeResultTB.Visibility = System.Windows.Visibility.Collapsed;
                try
                {
                    PrzService.IsUserPrizeDoneAsync(PhoneTB.Text,
                           (short)App.GetID(PrizeCM.SelectedItem.ToString()));
                    RunLoading.Show();
                }
                catch
                {
                    App.MessageBox.ShowDialog("用户号码校验失败，无法连接服务器");
                    this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";
                    PrizeResultTB.Visibility = System.Windows.Visibility.Visible;
                }
            }
            else
            {
                DoRunBtnClick();
            }
        }
        void PrzService_IsUserPrizeDoneCompleted(object sender, IsUserPrizeDoneCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("号码验证失败");
                }
                else if(e.Result.ID==-1)
                {
                    string msg = string.Empty;
                    msg = string.Format("抽奖号码为【{0}】，请确认。", PhoneTB.Text);
                    App.MessageBox.ShowDialog(msg, new Action(DoRunBtnClick), Title.Information);
                }
                else
                {
                    App.MessageBox.ShowDialog(string.Format("用户【{0}】已在【{1}】抽奖",
                        PhoneTB.Text, e.Result.Create_Time));
                    this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";

                    PrizeResultTB.Visibility = System.Windows.Visibility.Collapsed;
                    RunLoading.Stop();
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("用户号码校验失败，无法连接服务器");
                RunLoading.Stop();
                this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";
                PrizeResultTB.Visibility = System.Windows.Visibility.Visible;
            }
        }
        void DoRunBtnClick()
        {
            if (RunBtn.Content.ToString() == "开始")
            {

                RunLoading.Show();
                PrizeResultTB.Visibility = System.Windows.Visibility.Collapsed;
                RunBtn.Content = "停止";
            }
            else
            {
               
                try
                {
                   

                        PrzService.UploadPrizeResultAsync(PhoneTB.Text, 
                            (short)(App.GetID(PrizeCM.SelectedItem.ToString()))
                            , App.CurrentUser.UserID);
                  

                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("抽奖异常，" + ex.Message);
                    RunLoading.Stop();
                    this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";
                    PrizeResultTB.Visibility = System.Windows.Visibility.Visible;
                }
               
            }
        }
        void PrzService_UploadPrizeResultCompleted(object sender, UploadPrizeResultCompletedEventArgs e)
        {
            try
            {
                string msg = string.Empty;
                if (e.Result == -1)
                {
                    msg = "当前奖品已全部兑完";
                }
                else if (e.Result == -2)
                {
                    msg = "奖项概率设置异常，请联系管理员";
                }
                else if (e.Result == -999)
                {
                    msg = "抽奖失败，服务器异常";
                }
                else if (e.Result > 0)
                {
                    var list = PrizeItemList.ItemsSource as List<Prize_Items>;
                    msg = list.First(a => a.ID == e.Result).Prize_Item;
                }
                else
                {
                    throw new Exception("抽奖失败，未知异常");

                }
                PrizeResultTB.Text = msg;
            }
            catch
            {
                App.MessageBox.ShowDialog("抽奖异常，连接出错");
                this.PrizeResultTB.Text = "请点击【开始】，进行抽奖";
            }
            finally
            {
                RunLoading.Stop();
                PrizeResultTB.Visibility = System.Windows.Visibility.Visible;
                RunBtn.Content = "开始";

            }
        }

    }
}
